// 历史评价页面组件

const usePagerEffect = (changeFun) => {
  // 参数是分页的变更事件
  const { reactive } = Vue
  const pageData = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  const pageChange = ({ type, currentPage, pageSize, $event }) => {
    if (type === 'size') {
      // 如果是分页大小发生改变，则重置到第1页去
      pageData.currentPage = 1
    }
    changeFun()
  }
  return {
    pageData,
    pageChange
  }
}
const HistoryComponent = {
  template: `
    <div class="page-box">
      <div class="page-header">
        <div class="page-header-search">
          <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small" label-width="80px">
            <el-form-item label="病案号" prop="code" label-width="55px">
              <el-input type="text" :debounce="250" v-model="searchForm.code" placeholder="请输入病案号" clearable />
            </el-form-item>
            <el-form-item label="导入时间" prop="createAt">
              <el-date-picker
                v-model="searchForm.createAt"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
          <div class="search-btns">
            <el-button type="primary" @click="commitQuery">提交</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </div>
        </div>
      </div>
      <div class="page-main">
        <vxe-toolbar ref="xToolbar" custom>
          <template #buttons>            
            <el-dropdown>
              <el-button type="primary">
              导出Excel<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click.native="exportSelected">导出选中项(仅点评数据)</el-dropdown-item>                  
                  <el-dropdown-item @click.native="exportCommentedAll">导出所有历史点评</el-dropdown-item>
                  <el-dropdown-item @click.native="exportHistory('query')">导出所有查询(无点评)</el-dropdown-item>
                  <el-dropdown-item @click.native="exportHistory('allHistory')">导出所有历史数据(无点评)</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </vxe-toolbar>
        <vxe-table ref="xTable" resizable auto-resize
          highlight-hover-row
          highlight-current-row
          max-height="100%"
          :data="tableData">
          <vxe-column type="checkbox" width="60"></vxe-column>
          <vxe-column field="paytype" title="医疗付款方式" show-header-overflow></vxe-column>
          <vxe-column field="healthNo" title="健康卡号"></vxe-column>
          <vxe-column field="hospitalNum" title="住院次数"></vxe-column>
          <vxe-column field="code" title="病案号"></vxe-column>
          <vxe-column field="isChouYang" title="是否被抽样" show-header-overflow></vxe-column>
          <vxe-column field="sex" title="性别"></vxe-column>
          <vxe-column field="birthday" title="出生日期" width="80"></vxe-column>
          <vxe-column field="age" title="年龄"></vxe-column>
          <vxe-column field="country" title="国籍"></vxe-column>
          <vxe-column field="BZYZSNL" title="BZYZSNL"></vxe-column>
          <vxe-column field="babyBirthWeight" title="新生儿出生体重" show-header-overflow></vxe-column>
          <vxe-column field="babyHospitalWeight" title="新生儿入院体重" show-header-overflow></vxe-column>
          <vxe-column field="createAt" title="导入时间" width="80" show-header-overflow show-overflow></vxe-column>
          <vxe-column field="commentat" title="点评时间" width="100" fixed="right" show-header-overflow show-overflow></vxe-column>
          <vxe-column title="操作" width="120" fixed="right" show-overflow>
            <template #default="{ row }">
              <el-button type="warning" v-if="row.commentat" icon="el-icon-edit" @click="onShowComment(row)">更新点评</el-button>
              <el-button type="primary" v-else icon="el-icon-edit" @click="onShowComment(row)">点评</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="page-footer">
      <vxe-pager
        background
        v-model:current-page="pageData.currentPage"
        v-model:page-size="pageData.pageSize"
        :total="pageData.total"
        @page-change="pageChange"
        :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
      </vxe-pager>
      </div>
    </div>
    <comment-dialog v-model:dialogVisible="dialogVisible" :rowObj="rowObj" @on-confirm="onCommentConfirm"></comment-dialog>
  `,
  setup() {
    const { ref, reactive, watch, nextTick, onActivated } = Vue
    const { ElMessage } = ElementPlus
    const { pageData, pageChange } = usePagerEffect(loadHistoryData)
    const rowObj = ref({})

    const dialogVisible = ref(false)
    const onShowComment = (row) => {
      rowObj.value = { ...row }
      dialogVisible.value = true
    }
    const onCommentConfirm = () => {
      dialogVisible.value = false
      loadHistoryData() // 点评完成之后更新列表数据
    }

    const searchForm = reactive({
      code: '',
      createAt: []
    })
    const searchFormRef = ref(null)
    const tableData = ref([])

    const uploadSuccess = (response, file, fileList) => {
      if (response.code === 200) {
        console.log(response.data)
        tableData.value = response.data
        ElMessage.success(response.msg)
      }
    }

    watch(
      () => searchForm.code,
      () => {
        // 对表格数据进行搜索过滤
        pageData.currentPage = 1
        loadHistoryData()
      }
    )

    const commitQuery = () => {
      pageData.currentPage = 1
      loadHistoryData()
    }
    const resetQuery = () => {
      pageData.currentPage = 1
      searchForm.createAt = []
      if (searchForm.code) {
        searchForm.code = '' // 这里watch会自动去执行，所以不用查询
      } else {
        loadHistoryData()
      }
    }
    onActivated(() => {
      console.log('页面被激活了')
      resetQuery()
    })

    function loadHistoryData() {
      // 加载表格数据
      let params = {
        currentPage: pageData.currentPage,
        pageSize: pageData.pageSize,
        code: searchForm.code
      }
      if (searchForm.createAt && searchForm.createAt[0]) {
        params.createStart = searchForm.createAt[0]
      }
      if (searchForm.createAt && searchForm.createAt[1]) {
        params.createEnd = searchForm.createAt[1]
      }
      axios.post('history/page', params).then((res) => {
        const data = res.data.data
        console.log(data)
        const totalObj = data.pop()
        tableData.value = data
        pageData.total = totalObj.total * 1
      })
    }

    const xTable = ref({})
    const xToolbar = ref({})
    nextTick(() => {
      // 将表格和工具栏进行关联
      const $table = xTable.value
      const $toolbar = xToolbar.value
      $table.connect($toolbar)
    })

    // 导出选中项
    const exportSelected = () => {
      const $table = xTable.value
      const selectRecords = $table.getCheckboxRecords()
      const commentRecords = selectRecords.filter((x) => x.commentat)
      const codes = commentRecords.map((x) => x.code)
      if (!codes.length) {
        ElMessage.warning('请选择已点评数据导出')
        return
      }
      console.log(codes)
      commonExport({ codes }, 'selected')
    }
    // 导出所有的历史点评
    const exportCommentedAll = () => {
      commonExport(null, 'all')
    }

    const exportHistory = (t) => {
      if (t === 'query') {
        let params = {
          code: searchForm.code,
          createStart: (searchForm.createAt && searchForm.createAt[0]) || '',
          createEnd: (searchForm.createAt && searchForm.createAt[1]) || ''
        }
        commonExport(params, t)
      } else {
        commonExport(null, t)
      }
    }

    const commonExport = (params = {}, type) => {
      const titleObj = {
        selected: '导出选中.xlsx',
        all: '所有历史点评.xlsx',
        query: '导出所有查询记录.xlsx',
        allHistory: '所有历史数据.xlsx'
      }
      let excelTitle = titleObj[type] || '所有历史点评.xlsx'
      let url = '/comment/export'
      if (type === 'query' || type === 'allHistory') {
        url = '/history/export'
      }

      axios.post(url, params, { responseType: 'blob' }).then((res) => {
        const stream = res.data // 后端用stream返回Excel文件
        const blob = new Blob([stream])

        // 前端获取业务码，成功执行正常业务
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = excelTitle // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      })
    }

    // 导出
    const exportExcel = () => {
      axios.post('/comment/export', {}, { responseType: 'blob' }).then((res) => {
        console.log(res)
        const stream = res.data // 后端用stream返回Excel文件
        const blob = new Blob([stream])
        // if (response.status !== 200) {
        //   // 非正常业务码，执行错误处理
        //   // 注意：status字段名是团队自行定义的
        // }

        // 前端获取业务码，成功执行正常业务
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = '测试下载.xlsx' // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      })
    }

    return {
      rowObj,
      tableData,
      pageData,
      pageChange,
      searchForm,
      searchFormRef,
      uploadSuccess,
      xTable,
      xToolbar,
      dialogVisible,
      commitQuery,
      resetQuery,
      onShowComment,
      onCommentConfirm,
      exportExcel,
      exportSelected,
      exportCommentedAll,
      exportHistory
    }
  }
}
